import api from '@/odoojs/index.js'
import { computed } from 'vue'

export function useSubTree(props) {
  const Relation = computed(() => {
    if (!props.node) {
      return undefined
    }

    return api.relation_node(props.node)
  })

  const treeview = computed(() => {
    if (!Relation.value) {
      return undefined
    }
    return Relation.value.tree
  })

  const sheet = computed(() => {
    if (!treeview.value) {
      return {}
    }
    return treeview.value.get_arch_sheet({ parent_info: props.parentInfo })
  })

  function fields2cols(fields) {
    const cols = Object.keys(fields).map(fld => {
      const info = fields[fld] || {}
      //   console.log(fld, info)
      return {
        dataIndex: info.name,
        key: fld,
        title: info.string,
        ...info
      }
    })

    return cols
  }

  const columns = computed(() => {
    const cols91 = fields2cols(sheet.value)
    // console.log(cols91)
    const cols = cols91.filter(item => item.tagname === 'odoofield')

    if (cols.length === 0) {
      return [
        {
          dataIndex: 'display_name',
          key: 'display_name',
          title: '名称',
          widget: 'char',
          name: 'display_name'
        }
      ]
    }

    return cols
  })

  const treeInfo = computed(() => {
    const view = treeview.value
    if (!view) return {}
    const info = {
      model: view.model,
      metadata: view.metadata
    }

    // console.log(info)

    return { ...info }
  })

  return { treeInfo, columns }
}
